<template>
  <el-dialog v-model="isShowDialog"
             :before-close="handleClose"
             :title="title"
             draggable
             width="70%"
             append-to-body
  >
    <div style="height: 680px;overflow-x:hidden;">
      <div class="justify-content items-center" style="margin-bottom: 15px">
        <div class="plan">
          <span class="information"></span>
          <span class="informationText">基本信息</span>
        </div>
      </div>
      <el-form :inline="true" ref="formRef" :disabled="isView" :model="saveParams" label-width="120px" :rules="rules">
        <div style="display: flex;flex-wrap: wrap">
          <el-col :span="6">
            <el-form-item label="策略名称" prop="ployName">
              <el-input v-model="saveParams.ployName" placeholder="策略名称" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="仓库" prop="warehouseId">
              <el-select
                  :disabled="saveParams.ployId"
                  clearable
                  v-model="saveParams.warehouseId"
              >
                <template v-for="(item,index) in warehouseList" :key="index">
                  <el-option :label="item.warehouseName" :value="item.warehouseId"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="波次自动执行" prop="status">
              <el-select v-model="saveParams.status" style="width: 100%" clearable placeholder="波次自动执行">
                <el-option label="启用" :value="0"></el-option>
                <el-option label="停用" :value="1"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="生效优先级别" prop="sort">
              <el-input v-model="saveParams.sort" @input="saveParams.sort=limitIntNumber(saveParams.sort)"
                        placeholder="生效优先级别" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最少出库单数量">
              <el-input v-model="saveParams.pickNumMin"
                        @input="saveParams.pickNumMin=limitIntNumber(saveParams.pickNumMin)"
                        placeholder="最少出库单数量"
                        clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="最多出库单数量">
              <el-input v-model="saveParams.pickNumMax"
                        @input="saveParams.pickNumMax=limitIntNumber(saveParams.pickNumMax)"
                        placeholder="最多出库单数量"
                        clearable/>
            </el-form-item>
          </el-col>
        </div>

      </el-form>

      <div class="justify-content items-center" style="margin:15px 0">
        <div class="plan">
          <span class="information"></span>
          <span class="informationText">拣货路线（必填）</span>
        </div>
      </div>
      <el-row>
        <div style="display: flex;width: 100%;margin-bottom: 10px;">
          <div style="width: 50%">
            <el-radio v-model="saveParams.pickType" :label="0" size="large">全仓拣货</el-radio>
            <el-select
                v-model="pickUserId"
                placeholder="请分配拣货人员"
                style="width: 240px"
            >
              <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
              />
            </el-select>
          </div>
          <div style="width: 50%">
            <el-radio v-model="saveParams.pickType" :label="1" size="large">自定义拣货路线</el-radio>
            <el-select
                v-model="pickUserId2"
                placeholder="请分配拣货人员"
                style="width: 240px"
            >
              <el-option
                  v-for="item in userList"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
              />
            </el-select>
          </div>
        </div>
        <el-button v-if="!isView" icon="Plus" type="primary" @click="handleAdd">添加库位</el-button>
        <el-button v-if="!isView" icon="Delete" type="danger" @click="handleDel">删除所选</el-button>
      </el-row>
      <vxe-table
          ref="tableKwRef"
          border
          style="margin-top: 10px;"
          align="center"
          :data="tableKwList"
          height="200"
          :checkbox-config="{ trigger:'row'}"
          :row-config="{isCurrent: true, isHover: true}"
          :edit-rules="validKwRules"
      >
        <vxe-column type="checkbox" width="60"></vxe-column>
        <vxe-column field="sort" title="拣货顺序">
          <template #default="{row}">
            <el-input v-model="row.sort" :disabled="isView" @input="row.sort=limitIntNumber(row.sort)" clearable/>
          </template>
        </vxe-column>
        <vxe-column field="locationCode" title="库位编码"></vxe-column>
        <vxe-column field="locationName" title="库位位置">
        </vxe-column>
        <vxe-column field="rackNo" title="货架号"></vxe-column>
        <vxe-column field="areaName" title="库区"></vxe-column>
        <vxe-column field="warehouseName" title="仓库"></vxe-column>
      </vxe-table>

      <div class="justify-content items-center" style="margin:15px 0">
        <div class="plan">
          <span class="information"></span>
          <span class="informationText">发货方式（必填）</span>
        </div>
      </div>

      <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
        <template v-for="(item,index) in baler_type" :key="index">
          <el-tab-pane :label="item.label" :name="item.value">
            <el-row>
              <el-button v-if="!isView" icon="Plus" type="primary" @click="handleGoodsAdd(index)">添加商品</el-button>
              <el-button v-if="!isView" icon="Delete" type="danger" @click="handleGoodsDel(index)">删除所选</el-button>
              <div style="display: flex;margin-left: 20px;align-items: center">
                <div style="width: 160px;">多品时组合数量不能超过:</div>
                <el-input style="width: 120px;" v-model="ployDeliveryList[index].maxNum" :disabled="isView"
                          @input="ployDeliveryList[index].maxNum=limitIntNumber(ployDeliveryList[index].maxNum)"
                          clearable/>
              </div>
            </el-row>
            <vxe-table
                :ref="'tableGoodsRef'+index"
                border
                style="margin-top: 10px;"
                align="center"
                :data="ployDeliveryList[index].ploySkuList"
                height="200"
                :checkbox-config="{ trigger:'row'}"
                :row-config="{isCurrent: true, isHover: true}"
            >
              <vxe-column type="checkbox" width="80"></vxe-column>
              <vxe-column type="seq" width="80" title="序号"></vxe-column>
              <vxe-column field="skuCode" title="SKU编号"></vxe-column>
              <vxe-column field="skuName" title="商品名称"></vxe-column>
              <vxe-column field="coverUrl" width="180" title="商品图片">
                <template #default="{row}">
                  <ImagePreview v-if="row.coverUrl" :width="150" :height="50" :src="row.coverUrl"></ImagePreview>
                </template>
              </vxe-column>
              <vxe-column field="classifyName" title="商品分类"></vxe-column>
            </vxe-table>
          </el-tab-pane>
        </template>
      </el-tabs>
    </div>

    <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" v-if="!isView" @click="clickSubmit"> 提交 </el-button>
          <el-button @click="handleClose">取消</el-button>
        </span>
    </template>
    <!--添加拣货路线-->
    <SelStorageLocation v-if="openSelDialog" :openSelDialog="openSelDialog" :filterData="tableKwList"
                        :companyId="sysUserInfo.companyId"
                        :warehouseId="saveParams.warehouseId"
                        @closeSelDialog="closeSelDialog"></SelStorageLocation>
    <!--    添加商品-->
    <SelStorageGoods v-if="openSelGoodsDialog" :openSelGoodsDialog="openSelGoodsDialog"
                     :companyId="sysUserInfo.companyId"
                     :warehouseId="saveParams.warehouseId"
                     :filterData="tableGoodsList"
                     @closeSelDialog="closeSelGoodsDialog"></SelStorageGoods>

  </el-dialog>

</template>

<script setup>
import {getCurrentInstance, onMounted, ref} from "vue";
import SelStorageLocation from "@/views/outStorage/wavePickTacticsManagement/component/selStorageLocation.vue";
import SelStorageGoods from "@/views/outStorage/wavePickTacticsManagement/component/selStorageGoods.vue";
import ImagePreview from "@/components/ImagePreview/index.vue";
import {batchPloySaveBatchPloy} from "@/api/scApi";
import {getCompanySelect, getWarehouseSelect, listUser} from "@/api/system/user";
import SelB2bInstorageGoods from "@/views/inStorage/b2bInStorage/component/selB2bInstorageGoods.vue";

const {proxy} = getCurrentInstance()
const {baler_type} = proxy.useDict("baler_type");
let tableKwList = ref([])
let saveParams = ref({
  'pickType': 0
})
let pickUserId=ref("") //全仓拣货人
let pickUserId2=ref("")//自定义路线 人
// 表单校验
const rules = ref({
  ployName: [{required: true, message: "策略名称不能为空", trigger: "blur"}],
  status: [{required: true, message: "波次自动执行不能为空", trigger: "change"}],
  sort: [{required: true, message: "生效优先级别不能为空", trigger: "blur"}],
  warehouseId: [{required: true, message: "所属仓库不能为空", trigger: "change"}],
});
const validKwRules = ref({
  sort: [
    {required: true, message: '拣货顺序不能为空'},
  ],
})
const props = defineProps({
  isShowDialog: {
    type: Boolean,
    default: false
  },
  title: {
    type: String
  },
  detailData: {type: Object},
  isView: {type: Boolean}
})

const emits = defineEmits(['cancel'])
onMounted(() => {
  getUserList()
  if (JSON.stringify(props.detailData) != '{}') {
    saveParams.value = props.detailData
    tableKwList.value = props.detailData.ployLineList
    ployDeliveryList.value = props.detailData.ployDeliveryList

    if(saveParams.value.pickType ===0){
      //全仓拣货
      pickUserId.value =  saveParams.value.pickUserId
    }else{
      pickUserId2.value = saveParams.value.pickUserId
    }
  }

  if (baler_type.value.length > 0) {
    activeName.value = baler_type.value[0].value
    let len = baler_type.value.length - ployDeliveryList.value.length //差值 差几条数据就补几条发货方式的数据
    for (let i = 0; i < len; i++) {
      ployDeliveryList.value.push({}) //添加空数据 保证代码不报错 能正常绑定v-model
    }
    ployDeliveryList.value[0].deliveryValue = activeName.value
  }
  getWarehouse()

})

watch(() => baler_type.value, () => {
  activeName.value = baler_type.value[0].value
  let len = baler_type.value.length - ployDeliveryList.value.length //差值 差几条数据就补几条发货方式的数据
  for (let i = 0; i < len; i++) {
    ployDeliveryList.value.push({})
  }
  ployDeliveryList.value[0].deliveryValue = activeName.value

})

function handleClose() {
  emits('cancel')
}

//添加商品事件处理
let openSelDialog = ref(false)

function handleAdd() {
  openSelDialog.value = true
}

//库位关闭
function closeSelDialog(data) {
  openSelDialog.value = false
  if (data) {
    tableKwList.value = [...tableKwList.value, ...data]
  }
}

//删除所选
function handleDel() {
  let selRows = proxy.$refs.tableKwRef.getCheckboxRecords()
  let a = tableKwList.value
  let filtered = a.filter(obj => !selRows.some(bObj => bObj.locationId === obj.locationId));
  tableKwList.value = filtered
}

let ployDeliveryList = ref([])//发货方式集合
let tableGoodsList = ref([])//过滤的拣货商品
let openSelGoodsDialog = ref(false)
let tabIndex = ref(0)

function handleGoodsAdd(index) {
  tabIndex.value = index
  openSelGoodsDialog.value = true
}

function closeSelGoodsDialog(data) {
  openSelGoodsDialog.value = false
  if (data) {
    let tableGoods = ployDeliveryList.value[tabIndex.value].ploySkuList || []
    tableGoods = [...tableGoods, ...data]
    ployDeliveryList.value[tabIndex.value].ploySkuList = tableGoods
    tableGoodsList.value = tableGoods
  }
}

function handleGoodsDel(index) {
  let selRows = proxy.$refs['tableGoodsRef'+index][0].getCheckboxRecords()
  let a = ployDeliveryList.value[index].ploySkuList
  let filtered = a.filter(obj => !selRows.some(bObj => bObj.skuId === obj.skuId));
  ployDeliveryList.value[index].ploySkuList= filtered
}

const clickSubmit = async () => {
  if (saveParams.value.pickType===1 && tableKwList.value.length === 0 ) {
    proxy.$modal.msgWarning("请先添加拣货路线！")
    return
  }
  if (ployDeliveryList.value.length === 0) {
    proxy.$modal.msgWarning("请先添加发货方式！")
    return
  }

  if(saveParams.value.pickType ===0){
    //全仓拣货
    saveParams.value.pickUserId = pickUserId.value
  }else{
    saveParams.value.pickUserId = pickUserId2.value
  }

  const $table = proxy.$refs.tableKwRef
  if ($table) {
    const errMap = await $table.validate(true)
    if (errMap) {
      console.log('校验失败！')
    } else {
      console.log('校验成功！')
      proxy.$refs.formRef.validate((valid) => {
        if (valid) {
          saveParams.value.ployLineList = tableKwList.value
          saveParams.value.ployDeliveryList = ployDeliveryList.value
          batchPloySaveBatchPloy(saveParams.value).then(res => {
            if (res.code === 200) {
              proxy.$modal.msgSuccess('保存成功')
              emits('cancel', true)
            }
          })
        }
      })
    }
  }

}

const activeName = ref(0)

function handleClick(obj) {
  ployDeliveryList.value[obj.index].deliveryValue = activeName.value

  tableGoodsList.value = ployDeliveryList.value[obj.index].ploySkuList
}


/** 查询用户列表 */
let userList=ref([])
function getUserList() {
  let params = {
    pageNum: 1,
    pageSize:999,
    param: {}
  }
  listUser(params).then(res => {
    userList.value = res.data;
  });
};

//获取仓库下拉数据
let warehouseList = ref([])
const sysUserInfo=JSON.parse(localStorage.getItem("userInfo"))
function getWarehouse(){
  getWarehouseSelect({'companyId': sysUserInfo.companyId}).then(res => {
    warehouseList.value = res.data
  })
}

</script>

<style scoped lang="scss">

</style>